#!/usr/bin/env python
# -*-coding: utf-8-*-
# AUTHOR ：Arthur
# DATE   ：2016-10-19
# INTRO  ：
# VERSION：0.1

import subprocess
import random
import threading
import config
import os


class CheckTask(object):
    """
    多线程检查ip可用性，将可用的ip保存到config.PEER_TEMP中
    """

    # 设置文件锁
    file_lock = threading.Lock()

    @staticmethod
    def check(ip):
        """
        传入待检测ip
        :param ip:
        :return:
        """
        # 去验证请求的ip地址
        urls = ["www.baidu.com",
                "www.163.com",
                ]
        url = random.choice(urls)
        try:
            cmd = 'curl -I -x {} -o /dev/null -s -w {} {}'.format(ip, '%{http_code}', url)
            r = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT, timeout=config.TIMEOUT).decode('utf-8')
            if r == "200":
                # 写文件的时候使用锁
                with CheckTask.file_lock:
                    with open(config.PEER_TEMP_FILE, "a+") as f:
                        print(ip, file=f)

        except Exception as e:
            e

    @staticmethod
    def start(ips):
        """
        传入ip列表，启用多线程处理列表中的ip
        :param ips:
        """
        # 检查缓存文件是否存在，如果存在将其删除
        if os.path.exists(config.PEER_TEMP_FILE):
            os.remove(config.PEER_TEMP_FILE)
        # 开启多线程
        threads = []
        for ip in ips:
            thr = threading.Thread(target=CheckTask.check, args=(ip,),daemon=True)
            threads.append(thr)
            thr.start()
        # 等待多线程执行完毕
        for thr in threads:
            thr.join()
